<template>
  <el-card shadow="never">
    <el-form :model="searchForm" label-width="auto" :inline="true">
      <el-row>
        <el-col :span="6">
          <el-form-item label="订单编号" style="width: 85%">
            <el-input
              v-model="searchForm.orderSn"
              placeholder="请输入 订单编号"
              class="!w-[240px]"
              size="small"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订单名称" style="width: 85%">
            <el-input
              v-model="searchForm.orderName"
              placeholder="请输入 订单名称"
              class="!w-[240px]"
              size="small"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同名称" style="width: 85%">
            <el-select
              v-model="searchForm.contractName"
              clearable
              filterable
              remote
              remote-show-suffix
              placeholder="请选择 合同名称"
              :remote-method="getContractNameList"
              size="small"
            >
              <el-option
                v-for="item in contractOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目名称" style="width: 85%">
            <el-select
              v-model="searchForm.projectName"
              clearable
              filterable
              remote
              remote-show-suffix
              placeholder="请选择 项目名称"
              :remote-method="getProjectNameList"
              size="small"
            >
              <el-option
                v-for="item in projectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                class="!w-[500px]"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="text-align: right">
        <el-col :span="24" style="text-align: right">
          <!-- <el-button color="#1E3485" size="small" :icon="Refresh"
            >生成对账</el-button
          > -->
          <el-button
            color="#1E3485"
            size="small"
            icon="Download"
            @click="getList('', true)"
          >导出</el-button
          >
          <el-button
            color="#1E3485"
            size="small"
            :icon="Search"
            @click="
              tablePage.currentPage = 1;
              getlist('1');
            "
            >搜索</el-button
          >
          <el-button
            type="default"
            size="small"
            :icon="Delete"
            @click="clearAllFields"
            >清空</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <el-form style="margin-top: 20px">
      <vxe-table
        border
        min-height="300"
        header-align="center"
        :column-config="{ resizable: true }"
        :row-config="{ isHover: true }"
        :data="TableData"
        size="mini"
      >
        <vxe-column type="checkbox" width="40" fixed="left" disabled />
        <vxe-column
          type="seq"
          title="序号"
          fixed="left"
          width="60"
          align="center"
        />
        <vxe-column
          field="orderSn"
          title="订单编号"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="orderName"
          title="订单名称"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="contractName"
          title="合同名称"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="projectName"
          title="项目名称"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="createdAt"
          title="订单发起时间"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="shipmentAt"
          title="供货时间"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="shipmentFiles"
          title="供货凭证"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="taxTotalPrice"
          title="供货含税总金额(元)"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="reconciliationStatus"
          title="对账"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column
          field="supplyStatus"
          title="状态"
          width="200"
          show-header-overflow
          show-overflow="title"
          show-footer-overflow
        />
        <vxe-column title="操作" fixed="right" width="200" align="center">
          <!-- 操作列按钮 -->
          <template v-slot="{ row }">
            <!-- <vxe-button
              v-if="
                row.supplyStatus == '待上传送货单' ||
                row.supplyStatus == '待项目验收'
              "
              mode="text"
              @click="withdraw(row)"
              >撤回</vxe-button
            > -->
            <vxe-button
              v-if="row.supplyStatus == '待上传送货单'"
              mode="text"
              @click="Uploaddelivery(row)"
              >上传送货单</vxe-button
            >
            <vxe-button
              v-if="row.supplyStatus == '待云采确认'"
              mode="text"
              @click="
                toDetail(
                  {
                    id: row.id,
                    title: '',
                    action: 'YCQRSupplyList'
                  },
                  'YCQRSupplyList'
                )
              "
              >云采确认</vxe-button
            >
            <vxe-button
              mode="text"
              @click="
                toDetail(
                  {
                    id: row.id,
                    title: '',
                    action: 'view'
                  },
                  'viewSupplyList'
                )
              "
              >查看</vxe-button
            >
          </template>
        </vxe-column>
      </vxe-table>
      <vxe-pager
        v-model:current-page="tablePage.currentPage"
        v-model:page-size="tablePage.pageSize"
        :layouts="[
          'Sizes',
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'FullJump',
          'Total'
        ]"
        :total="tablePage.total"
        size="small"
        @page-change="handlePageChange"
      />
    </el-form>
    <delivery :id="ID" :visible="dialogVisible" @close="closeSales" />
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { Delete, Search, Edit, Refresh } from "@element-plus/icons-vue";
import { VxePagerEvents } from "vxe-table";
import { useRouter, useRoute } from "vue-router";

import { getsosupplylist } from "@/api/ERP_SupplyManage";

import { useDetail } from "./components/utils/hooks";
import { ElMessage, ElMessageBox } from "element-plus";
import delivery from "./components/dialog/delivery.vue";

import { getProjectList } from "@/api/ERP_public";
import { getProcureContractsList } from "@/api/ERP_procure";
import {http} from "@/utils/http";
import {baseUrlApi} from "@/store/utils";
// 路由跳转
const route = useRoute();
const { toDetail, router } = useDetail();

onMounted(async () => {
  // getDZZT();
  // getDDZT();
  // getKPZT();
  if (route.query.title) {
    let stringValue: string = route.query.title as string;
  }
  getlist();
});

// 表单字段
const searchForm = reactive({
  orderSn: "", // 订单编号
  orderName: "", // 订单名称
  contractName: "", //合同名称
  projectName: "" //项目名称
});
//字典
const Options = reactive([]);

// 表格数据
const TableData = ref([]);

// 表格分页配置
const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10
});

// 获取供货清单列表
const getlist = async (query?: string, isExport) => {
  if (query === "1") {
    tablePage.currentPage = 1;
  }
  if (route.query.id) {
    let params: any = {};
    params.contractMethod = 1
    params.orderSn = searchForm.orderSn;
    params.applyId = route.query.id;
    // params.orderName = route.query.title;
    params.projectName = searchForm.projectName;
    params.contractName = searchForm.contractName;
    if(isExport) {
      await http.request('get',baseUrlApi("posupply/export/file"), {params})
      return
    }
    params.pageIndex = tablePage.currentPage;
    params.pageSize = tablePage.pageSize;
    getsosupplylist(params).then((response: any) => {
      response.data.records.forEach(res => {
        // 文件名称
        if (res.shipmentFiles) {
          const jsonObject = JSON.parse(res.shipmentFiles);
          jsonObject.forEach(item => {
            res.shipmentFiles = item.name;
          });
        }
        //订单发起时间
        if (res.createdAt) {
          const date = new Date(res.createdAt);
          res.createdAt =
            date.getFullYear() +
            "-" +
            (date.getMonth() + 1) +
            "-" +
            date.getDate();
        }
        //供货时间
        if (res.shipmentAt) {
          const date = new Date(res.shipmentAt);
          res.shipmentAt =
            date.getFullYear() +
            "-" +
            (date.getMonth() + 1) +
            "-" +
            date.getDate();
        }
        //对账状态
        if (res.reconciliationStatus == "0") {
          res.reconciliationStatus = "未对账";
        } else if (res.reconciliationStatus == "1") {
          res.reconciliationStatus = "对账中";
        } else if (res.reconciliationStatus == "2") {
          res.reconciliationStatus = "已对账";
        } else if (res.reconciliationStatus == "3") {
          res.reconciliationStatus = "部分对账";
        } else if (res.reconciliationStatus == "4") {
          res.reconciliationStatus = "云采已确认";
        }
        //状态
        if (res.supplyStatus == "0") {
          res.supplyStatus = "供货清单未提交";
        } else if (res.supplyStatus == "1") {
          res.supplyStatus = "待上传送货单";
        } else if (res.supplyStatus == "2") {
          res.supplyStatus = "撤回";
        } else if (res.supplyStatus == "3") {
          res.supplyStatus = "云采确认驳回";
        } else if (res.supplyStatus == "4") {
          res.supplyStatus = "待项目验收";
        } else if (res.supplyStatus == "5") {
          res.supplyStatus = "项目验收完成";
        } else if (res.supplyStatus == "6") {
          res.supplyStatus = "待云采确认";
        }
      });
      TableData.value = response.data.records;
      tablePage.total = response.data.totalElements;
    });
    if (query) {
      setTimeout(() => {
        getsosupplylist;
      }, 1500);
    }
  } else {
    let params: any = {};
    params.orderSn = searchForm.orderSn;
    params.orderName = searchForm.orderName;
    params.projectName = searchForm.projectName;
    params.contractName = searchForm.contractName;
    if(isExport) {
      await http.request('get',baseUrlApi("posupply/export/file"), {params})
      return
    }
    params.contractMethod = 1
    params.pageIndex = tablePage.currentPage;
    params.pageSize = tablePage.pageSize;
    getsosupplylist(params).then((response: any) => {
      response.data.records.forEach(res => {
        // 文件名称
        if (res.shipmentFiles) {
          const jsonObject = JSON.parse(res.shipmentFiles);
          jsonObject.forEach(item => {
            res.shipmentFiles = item.name;
          });
        }
        //订单发起时间
        if (res.createdAt) {
          const date = new Date(res.createdAt);
          res.createdAt =
            date.getFullYear() +
            "-" +
            (date.getMonth() + 1) +
            "-" +
            date.getDate();
        }
        //供货时间
        if (res.shipmentAt) {
          const date = new Date(res.shipmentAt);
          res.shipmentAt =
            date.getFullYear() +
            "-" +
            (date.getMonth() + 1) +
            "-" +
            date.getDate();
        }
        //对账状态
        if (res.reconciliationStatus == "0") {
          res.reconciliationStatus = "未对账";
        } else if (res.reconciliationStatus == "1") {
          res.reconciliationStatus = "对账中";
        } else if (res.reconciliationStatus == "2") {
          res.reconciliationStatus = "已对账";
        } else if (res.reconciliationStatus == "3") {
          res.reconciliationStatus = "部分对账";
        } else if (res.reconciliationStatus == "4") {
          res.reconciliationStatus = "云采已确认";
        }
        //状态
        if (res.supplyStatus == "0") {
          res.supplyStatus = "供货清单未提交";
        } else if (res.supplyStatus == "1") {
          res.supplyStatus = "待上传送货单";
        } else if (res.supplyStatus == "2") {
          res.supplyStatus = "撤回";
        } else if (res.supplyStatus == "3") {
          res.supplyStatus = "云采确认驳回";
        } else if (res.supplyStatus == "4") {
          res.supplyStatus = "待项目验收";
        } else if (res.supplyStatus == "5") {
          res.supplyStatus = "项目验收完成";
        } else if (res.supplyStatus == "6") {
          res.supplyStatus = "待云采确认";
        }
      });
      TableData.value = response.data.records;
      tablePage.total = response.data.totalElements;
    });
    if (query) {
      setTimeout(() => {
        getsosupplylist;
      }, 1500);
    }
  }
};

// 清空按钮点击事件
const clearAllFields = () => {
  // 重置SearchForm对象的所有属性
  for (const key in searchForm) {
    if (searchForm.hasOwnProperty(key)) {
      if (key === "signDate") {
        // searchForm[key] = [];
        searchForm[key] = null;
      } else {
        searchForm[key] = "";
      }
    }
  }
};

// 表格分页事件
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  getlist();
};

const withdraw = row => {
  ElMessageBox.confirm("撤回后可再次编辑，确认撤回提交的供货?", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      ElMessage({
        message: "撤回成功",
        type: "success"
      });
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "Delete canceled"
      // });
    });
};

const ID = ref();
const Uploaddelivery = row => {
  ID.value = row.id;
  showSalescontract();
};

//弹窗打开
let dialogVisible = ref(false);
function showSalescontract() {
  dialogVisible.value = true;
}
function closeSales(val: boolean) {
  dialogVisible.value = false;
  getlist();
}

// 项目名称选择
let projectOptions = ref([]);
// 项目名称列表下拉框
const getProjectNameList = (query: string) => {
  getProjectList({
    pageIndex: 1,
    pageSize: 10,
    projectName: query
  }).then(response => {
    projectOptions.value = (response as any).data.records.map(item => ({
      label: item.projectName,
      value: item.projectName
    }));
  });
  if (query) {
    setTimeout(() => {
      getProjectList;
    }, 1500);
  }
};
// 合同名称选择
let contractOptions = ref([]);
// 合同名称列表下拉框
const getContractNameList = (query: string) => {
  getProcureContractsList({
    pageIndex: 1,
    pageSize: 10,
    contractType: "0",
    contractName: query
  }).then(response => {
    contractOptions.value = (response as any).data.records.map(item => ({
      label: item.contractName,
      value: item.contractName
    }));
  });
  if (query) {
    setTimeout(() => {
      getProcureContractsList;
    }, 1500);
  }
};
</script>

<style lang="scss" scoped></style>
